<template>
  <div>
    <KiFormDialog
      :show.sync="dialogVisible"
      v-if="dialogVisible"
      :title="params.title"
      v-model="form"
      :submit="submit"
      :readonly="readonly"
      ref="formRef"
    >
      <template #el-form>
        <div class="form-title">基本信息</div>
        <el-form-item label="商户ID" v-if="readonly">
          <el-input v-model="form.merchantId"></el-input>
        </el-form-item>
        <el-form-item label="企业" prop="companyId" verify>
          <KiSelect
            style="width: 100%"
            v-model="form.companyId"
            placeholder="请选择企业"
            :disabled="showType != 'add'"
            :options="companyList"
            :props="{ value: 'id', label: 'name' }"
          />
        </el-form-item>
        <el-form-item label="引入方" prop="belongAgencyName" v-if="readonly">
          <el-input
            v-model.trim="form.belongAgencyName"
            maxlength="45"
          ></el-input>
        </el-form-item>
        <el-form-item label="商户名称" prop="name" verify>
          <el-input
            v-model.trim="form.name"
            placeholder="请输入商户名称"
            maxlength="45"
          ></el-input>
        </el-form-item>
        <el-form-item label="商户客服电话" prop="phone" verify>
          <el-input
            v-model.trim="form.phone"
            maxlength="20"
            placeholder="请输入商户客服电话"
          ></el-input>
        </el-form-item>
        <el-form-item label="商户联系人" prop="contracts" verify>
          <el-input
            v-model="form.contracts"
            maxlength="20"
            placeholder="请输入商户联系人"
          ></el-input>
        </el-form-item>
        <el-form-item label="商户联系人手机号" prop="contactPhone" verify>
          <el-input
            v-model.trim="form.contactPhone"
            maxlength="20"
            placeholder="请输入商户联系人手机号"
          ></el-input>
        </el-form-item>

        <!-- <el-form-item
          label="平台手续费(%)"
          prop="plateformCharge"
          :rules="{ validator: percentage }"
        >
          <el-input
            v-model="form.plateformCharge"
            :disabled="readonly || isMerchant"
          ></el-input>
        </el-form-item> -->

        <el-form-item label="商户营业时间" prop="businessTime" verify>
          <el-input
            v-model="form.businessTime"
            maxlength="200"
            placeholder="请输入商户营业时间"
          ></el-input>
        </el-form-item>

        <el-form-item label="商户地址" prop="placeCode" verify class="mb20">
          <AllRegionSelect ref="RegionSelect" v-model="form.placeCode" />
        </el-form-item>
        <el-form-item label="详情地址" prop="address" verify class="mb20">
          <el-input
            v-model="form.address"
            clearable
            maxlength="100"
            show-word-limit
            placeholder="请选择详细位置"
          >
            <el-button slot="prepend" @click="showCoordPicker = true">
              地图选点
            </el-button>
          </el-input>
          <CoordPicker
            :show.sync="showCoordPicker"
            :lng.sync="form.longitude"
            :lat.sync="form.latitude"
            :address.sync="form.address"
            :city="$refs.RegionSelect && $refs.RegionSelect.mLabel"
          />
        </el-form-item>
        <div class="flex">
          <el-form-item prop="longitude" verify class="flex-1">
            <el-input v-model="form.longitude" placeholder="请输入经度">
              <template slot="prepend">经度</template>
            </el-input>
          </el-form-item>
          <el-form-item prop="latitude" verify class="flex-1">
            <el-input v-model="form.latitude" placeholder="请输入纬度">
              <template slot="prepend">纬度</template>
            </el-input>
          </el-form-item>
        </div>
        <el-form-item label="logo" prop="logo">
          <Imgpond :count="1" v-model="form.logo" fixed-ratio="1/1" />
        </el-form-item>
        <el-form-item label="商户资质" prop="license" verify>
          <!-- <upload
            dir="img"
            :files-url.sync="form.license"
            :limit="10"
            
            :uploading.sync="isUploading"
          /> -->
          <Imgpond :count="10" v-model="form.license" value-type="string" />
        </el-form-item>

        <div class="form-title">平台手续费</div>
        <el-form-item label="手续费计费模式" prop="plateformCharge">
          <el-radio
            v-model="form.platformChargeType"
            :label="1"
            :disabled="readonly || userInfo.companyId != '-1'"
          >
            商品统一费率
          </el-radio>
          <el-radio
            v-model="form.platformChargeType"
            :label="2"
            :disabled="readonly || userInfo.companyId != '-1'"
          >
            商品品类差异化费率
          </el-radio>
        </el-form-item>
        <template v-if="form.platformChargeType == 1">
          <el-form-item
            label="平台手续费(%)"
            prop="standCharge"
            :verify="{ type: 'number', maxDecimalLength: 1, gte: 0, lte: 30 }"
          >
            <el-input
              v-model="form.standCharge"
              :disabled="readonly || userInfo.companyId != '-1'"
              placeholder="请输入平台手续费"
            ></el-input>
          </el-form-item>
        </template>
        <template v-if="form.platformChargeType == 2">
          <el-form-item
            label="票务商品平台手续费(%)"
            prop="platformChargeInfo.ticketCharge"
            :verify="{ type: 'decimal', gte: 0, lte: 30 }"
          >
            <el-input
              v-model="form.platformChargeInfo.ticketCharge"
              :disabled="readonly || userInfo.companyId != '-1'"
              placeholder="请输入票务商品平台手续费"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="酒店商品平台手续费(%)"
            prop="platformChargeInfo.hotelCharge"
            verify
            :verify="{ type: 'decimal', gte: 0, lte: 30 }"
          >
            <el-input
              v-model="form.platformChargeInfo.hotelCharge"
              :disabled="readonly || userInfo.companyId != '-1'"
              placeholder="请输入酒店商品平台手续费"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="实物商品平台手续费(%)"
            prop="platformChargeInfo.goodsCharge"
            verify
            :verify="{ type: 'decimal', gte: 0, lte: 30 }"
          >
            <el-input
              v-model="form.platformChargeInfo.goodsCharge"
              :disabled="readonly || userInfo.companyId != '-1'"
              placeholder="请输入实物商品平台手续费"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="券类商品平台手续费(%)"
            prop="platformChargeInfo.couponCharge"
            verify
            :verify="{ type: 'decimal', gte: 0, lte: 30 }"
          >
            <el-input
              v-model="form.platformChargeInfo.couponCharge"
              :disabled="readonly || userInfo.companyId != '-1'"
              placeholder="请输入券类商品平台手续费"
            ></el-input>
          </el-form-item>
        </template>

        <!-- 微信支付渠道信息 -->
        <template v-if="readonly && form.payChannel.wechatPay">
          <div class="form-title">微信支付渠道信息</div>
          <el-form-item label="微信支付商户号" prop="payMchId">
            <el-input
              v-model.trim="form.payChannel.wechatPay.payMchId"
              :disabled="readonly || isMerchant"
              maxlength="20"
              placeholder="微信支付ID"
            ></el-input>
          </el-form-item>
          <el-form-item label="微信支付手续费(%)" verify prop="charge">
            <el-input
              v-model="form.payChannel.wechatPay.charge"
              :disabled="readonly || isMerchant"
              placeholder="请输入微信支付手续费"
            ></el-input>
          </el-form-item>
          <el-form-item label="商户模式" prop="mchType" verify>
            <el-select
              v-model="form.payChannel.wechatPay.mchType"
              :disabled="readonly || editMode"
            >
              <el-option label="服务商模式" :value="0"></el-option>
              <el-option label="普通商户模式" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="form.mchType == 1"
            label="支付key"
            prop="payKey"
            required
            verify
          >
            <el-input
              v-model="form.payChannel.wechatPay.payKey"
              maxlength="64"
              placeholder="请输入支付key"
            ></el-input>
          </el-form-item>
          <el-form-item
            v-if="form.mchType == 1"
            label="证书文件"
            prop="caPkFile"
            :required="!form.payChannel.wechatPay.caUpload"
          >
            <span>
              <el-tag
                v-if="
                  form.payChannel.wechatPay.caUpload && fileList.length == 0
                "
                size="small"
                type="success"
              >
                已上传
              </el-tag>
            </span>
          </el-form-item>
        </template>

        <template v-if="readonly && form.payChannel && form.payChannel.alipay">
          <div class="form-title">支付宝支付渠道信息</div>
          <el-form-item label="支付宝商户号（smid）" verify>
            <el-input
              v-model="form.payChannel.alipay.payMchId"
              placeholder="请输入支付宝商户号"
            ></el-input>
          </el-form-item>
          <el-form-item label="支付宝支付手续费（%）">
            <el-input v-model="form.payChannel.alipay.charge" verify></el-input>
          </el-form-item>
          <el-form-item label="支付登录账户">
            <el-input
              v-model="form.payChannel.alipay.alipayLoginId"
              :disabled="true"
              placeholder="请输入支付登录账户"
            ></el-input>
          </el-form-item>
        </template>

        <div class="form-title">公众号信息</div>
        <el-form-item label="公众号名称" prop="weChatName" :rules="requireName">
          <el-input
            v-model="form.weChatName"
            maxlength="20"
            show-word-limit
            placeholder="请输入公众号名称"
          ></el-input>
          <span style="color: #3568a0">
            （如果商户有公众号微商城，可以配置公众号信息，会在商品详情中显示，可以给店铺单独配置公众号信息。）
          </span>
        </el-form-item>
        <el-form-item
          label="公众号二维码"
          prop="qrCodeUrl"
          :rules="requireCodeUrl"
        >
          <Imgpond :count="1" v-model="form.qrCodeUrl" />
        </el-form-item>
        <div v-if="readonly">
          <div class="form-title">审核信息</div>
          <el-table :data="form.changeList" style="width: 100%">
            <el-table-column
              prop="statusName"
              label="变更状态"
            ></el-table-column>
            <el-table-column prop="changeTime" label="变更时间">
              <template v-slot="{ row }">
                {{ $dayjs(row.changeTime).format('YYYY-MM-DD HH:mm:ss') }}
              </template>
            </el-table-column>
            <el-table-column prop="changeMsg" label="备注"></el-table-column>
            <el-table-column prop="changeUser" label="操作人"></el-table-column>
          </el-table>
        </div>
      </template>
    </KiFormDialog>
  </div>
</template>
<script>
import { percentage } from '@/utils/validate-ruler.js'
import { RegionSelect } from 'region-select'
import { mapGetters } from 'vuex'

export default {
  components: {
    RegionSelect
  },
  props: ['areaList'],
  data() {
    let self = this
    const requireName = {
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (!value && self.form.qrCodeUrl) {
          callback(new Error('上传了公众号二维码，必须填写公众号名称'))
        }
        callback()
      }
    }
    const requireCodeUrl = {
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (!value && self.form.weChatName) {
          callback(new Error('填写了公众号名称，必须上传公众号二维码'))
        }
        callback()
      }
    }
    return {
      showCoordPicker: false,
      form: {},
      dialogVisible: false,
      params: {}, //当前页面类型参数
      ruleRequired: {
        required: true,
        message: '必填项'
      },
      isUploading: false,
      percentage,
      fileList: [],
      companyList: [],
      fileMaxSize: 1, //MB
      requireName: requireName,
      requireCodeUrl: requireCodeUrl,
      showType: ''
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    readonly() {
      return this.params.type === 'view'
    },
    editMode() {
      return this.params.type === 'edit'
    },
    isMerchant() {
      //是否商户账号, true商户 false平台
      return this.$store.getters.userInfo.userType == 1
    },
    isMerchantRequired() {
      if (this.isMerchant) {
        return this.ruleRequired
      }
      return null
    }
  },
  methods: {
    queryCompanyList(item = null) {
      this.companyList = []
      this.$POST('/sot-admin-api/merchant/merchant/queryCompanyList', {}).then(
        ({ data }) => {
          this.companyList = item ? [...data, item] : data
        }
      )
    },

    open(params) {
      this.showType = params.type
      if (params.type != 'add') {
        let data = {
          id: params.data.companyId,
          name: params.data.companyName
        }
        this.queryCompanyList(data)
      } else {
        this.queryCompanyList()
      }
      this.fileList = []
      this.params = params
      // 重置表单
      const $form = this.$refs.form
      $form && $form.resetFields()

      if (params.data) {
        let form = this.$lo.cloneDeep(params.data)
        if (form.platformChargeType == 1) {
          form.standCharge = form.platformChargeInfo.ticketCharge
        }
        this.form = form //当前表单的历史数据, 由父页面获取的
      } else {
        //新增页面,重置表单
        this.form = {
          platformChargeType: 1,
          platformChargeInfo: {}
        }
      }
      this.dialogVisible = true
    },
    submit() {
      if (this.params.type == 'add') {
        this.integration()
        this.$POST('/sot-admin-api/merchant/merchant/add', this.form)
          .then((data) => {
            this.$swal.success('保存成功')
            this.dialogVisible = false
            this.$emit('save')
          })
          .finally(() => {
            this.isUploading = false
          })
      } else if (this.params.type === 'edit') {
        this.integration()
        // 检测非必填项是否填完
        if (
          !this.form.phone ||
          !this.form.contracts ||
          !this.form.contactPhone ||
          !this.form.businessTime ||
          !this.form.placeCode ||
          !this.form.address ||
          !this.form.license
        ) {
          return this.$confirm(
            '信息不完善可能会导致该商户停用, 是否继续?',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
            .then(() => {
              return this.saveData(this.form)
            })
            .catch(() => {})
        } else {
          return this.saveData(this.form)
        }
      }
    },
    integration() {
      if (this.form.platformChargeType == 1) {
        this.form.platformChargeInfo.ticketCharge = this.form.standCharge
        this.form.platformChargeInfo.couponCharge = this.form.standCharge
        this.form.platformChargeInfo.goodsCharge = this.form.standCharge
        this.form.platformChargeInfo.hotelCharge = this.form.standCharge
      }
    },
    saveData(formData) {
      this.isUploading = true
      return this.$POST('/sot-admin-api/merchant/merchant/edit', formData)
        .then((data) => {
          this.$swal.success('编辑成功')
          this.dialogVisible = false
          this.$emit('save')
        })
        .finally(() => {
          this.isUploading = false
        })
    },
    getMapInfo(info) {
      this.$set(this.form, 'address', info.address)
      this.$set(this.form, 'longitude', info.lng)
      this.$set(this.form, 'latitude', info.lat)
    }
  }
}
</script>

<style scoped>
.form-title {
  font-size: 20px;
  font-weight: 600;
  letter-spacing: 3px;
  margin-bottom: 20px;
  margin-top: 0px;
}
</style>
